package com.zhangtai.modules.controller.member;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangtai.modules.controller.admin.JobController;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.controller.aouthLogin.MemberLoginController;
import com.zhangtai.modules.dao.*;
import com.zhangtai.modules.dto.DimissionInfoDto;
import com.zhangtai.modules.dto.EmployeeModelDto;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.DimissionInfoEntity;
import com.zhangtai.modules.entity.employee.DimissionSettlementEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.OldEmployeeEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.common.ImgUrlService;
import com.zhangtai.modules.service.dimission.DimissionInfoService;
import com.zhangtai.modules.service.dimission.DimissionService;
import com.zhangtai.modules.service.dimission.DimissionSettlementService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.vo.DimissionInfoVo;
import com.zhangtai.modules.vo.DimissionSettlemntVo;
import com.zhangtai.utils.*;
import com.zhangtai.utils.Excel.EntityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

//import com.zhangtai.modules.entity.DimissionAndEmployeeInfoEntity;

@RestController
@Api(tags="离职自助接口")
@RequestMapping("dimissionPC")
@Slf4j
public class DimissionMemberController {

    @Autowired
    private DimissionDao dimissionDao;
    @Autowired
    private DimissionService dimissionService;

    @Autowired
    private DimissionInfoDao dimissionInfoDao;
    @Autowired
    private DimissionInfoService dimissionInfoService;

    @Autowired
    private ImgUrlDao imgUrlDao;
    @Autowired
    private BaseMssqlServiceImpl jobService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private MemberLoginController memberLoginController;
    @Autowired
    private ImgUrlService imgUrlService;

    @Autowired
    private DimissionSettlementDao dimissionSettlementDao;
    @Autowired
    private DimissionSettlementService dimissionSettlementService;
    @Autowired
    private BaseMssqlServiceImpl commonService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private JobController jobController;

    
    @GetMapping("/getDimissionInfo")
    @ApiOperation(value = "分页查询离职信息")
    public R getDimissionInfo(   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest request)throws Exception{

        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        if(ObjectUtils.isEmpty(userInfo)){
            return R.error("请登录");
        }
        List<Long> orgIds = new ArrayList<>();
        orgIds.add(userInfo.getLong("depId"));
        String oid=userInfo.getString("id");
        List<Map<String,Object>> dimissionMap = dimissionInfoService.queryPageList(orgIds,
                oid,
                pageNum,pageSize);
        List<DimissionInfoDto> recordList  = EntityUtil.ListMapToListObj(dimissionMap, DimissionInfoDto.class);

        for(DimissionInfoDto dimissionInfoDto:recordList){
            Long orgId = dimissionInfoDto.getOrgId();
            String orgNameById = jobController.getOrgNameById(orgId);
            dimissionInfoDto.setOrgname(orgNameById);
            Long unitId = dimissionInfoDto.getUnitId();
            String unitname = jobController.getOrgNameById(unitId);
            dimissionInfoDto.setUnitname(unitname);
            Long jobId = dimissionInfoDto.getJobId();
            String jobName = jobController.getJobName(jobId);
            dimissionInfoDto.setJobname(jobName);

            List<String> annexUrl=new ArrayList<>();
            if(!StringUtils.isEmpty(dimissionInfoDto.getUrlIds())){
                String[] UrlList=dimissionInfoDto.getUrlIds().split(",");
                annexUrl= Arrays.asList(UrlList);
            }
            dimissionInfoDto.setFileUrlList(annexUrl);
        }
        Page page = new Page(pageNum,pageSize);
        page.setRecords(recordList);
        return  R.ok(new PageResult<DimissionInfoDto>(page));
    }

    @GetMapping("/getDimissionSettlementByProcessNumber")
    @ApiOperation(value = "根据流程编号查出离职结算信息")
    public R getDimissionSettlementByProcessNumber( @RequestParam(value = "processNumber") String processNumber,
                                 HttpServletRequest request)throws Exception{
        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        if(ObjectUtils.isEmpty(userInfo)){
            return R.error("请登录");
        }
        DimissionSettlementEntity dimissionSettlementEntity=dimissionSettlementDao.selectOne(new QueryWrapper<DimissionSettlementEntity>().eq("is_delete", 0).eq("process_number", processNumber));
        return  R.ok(dimissionSettlementEntity);

    }


    @PostMapping("/saveDimissionInfo")
    @ApiOperation(value="修改/保存员工自助离职信息")
    @Transactional
    public R saveDimissionInfo(@RequestBody @Valid DimissionInfoVo dimissionInfoVo, HttpServletRequest request) throws Exception {

        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        if(ObjectUtils.isEmpty(userInfo)){
            return R.error("请登录");
        }
        String oid=userInfo.getString("id");
        DimissionInfoEntity dimissionInfoEntity= BeanUtilsMabach.doToDto(dimissionInfoVo,DimissionInfoEntity.class);
        ArrayList<String> fileUrlList=dimissionInfoVo.getUrlIdsList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(dimissionInfoEntity.getOid(), fileUrlList, "离职申请附件",8);
        }
        dimissionInfoEntity.setUrlIds(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));
        if(dimissionInfoVo.getId()==null) {
            long id = snowflakeIdWorker.nextId();
            String processNumber = getDimissionInfoNum();
            dimissionInfoEntity.setId(id);
            dimissionInfoEntity.setApplyDepartment(userInfo.getString("department"));
            dimissionInfoEntity.setIsDelete(0);
            dimissionInfoEntity.setCreateTime(new Date());
            dimissionInfoEntity.setRurnoverStatus(0);
            dimissionInfoEntity.setIsRemind(0);
            dimissionInfoEntity.setMode("0");
            dimissionInfoEntity.setDimissionType("0");
            dimissionInfoEntity.setUnitId(userInfo.getLong("depId"));
            dimissionInfoEntity.setProcessNumber(processNumber);
            dimissionInfoService.saveE(dimissionInfoEntity);
        }else {
            dimissionInfoService.updateByIdE(dimissionInfoEntity);
        }
        return  R.ok(String.valueOf(dimissionInfoEntity.getId()));
    }

    @DeleteMapping("/deleteDimissionInfo")
    @ApiOperation(value = "删除员工离职信息")
    @Transactional
    public R deleteDimissionInfo(@RequestParam(value = "id" ) String id){
        DimissionInfoEntity dimissionInfoEntity = dimissionInfoDao.selectOne(new QueryWrapper<DimissionInfoEntity>().eq("id",id).eq("is_delete", 0));
        if(!org.springframework.util.ObjectUtils.isEmpty(dimissionInfoEntity)) {
            dimissionInfoEntity.setIsDelete(1);
            dimissionInfoDao.updateById(dimissionInfoEntity);
        }
        return R.ok();
    }

    @GetMapping("/queryDimissionSettlementList")
    @ApiOperation(value = "新分页查询离职结算列表")
    public R<PageResult<DimissionInfoDto>> queryDimissionSettlementList(@RequestParam(value = "name", required = false) String name,
                                                                        @RequestParam(value = "code", required = false) String code,
                                                                        @RequestParam(value = "hiredateStart", required = false) String hiredateStart,
                                                                        @RequestParam(value = "hiredateEnd", required = false) String hiredateEnd,
                                                                        @RequestParam(value = "jobLevelId", required = false) Long jobLevelId, //职级id
                                                                        @RequestParam(value = "lineId", required = false) Long lineId, //专业职级id
                                                                        @RequestParam(value = "jobSystemId", required = false) Long jobSystemId, //专业职级id
                                                                        @RequestParam(value = "status",  required = false) Integer status, //审批状态
                                                                        @RequestParam(value = "processingStatus" ,required = false) Integer processingStatus, //处理状态
                                                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                        HttpServletRequest request)throws Exception{
        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        if(ObjectUtils.isEmpty(userInfo)){ return R.error("请先登录");}
        List<Long> orgIds = new ArrayList<>();
        orgIds.add(userInfo.getLong("depId"));

        Page page = new Page(pageNum,pageSize);
        List<DimissionInfoDto>  recordList  = dimissionSettlementDao.getDimissionInfoList(orgIds,userInfo.getString("id"),
                name,
                code,
                hiredateStart,
                hiredateEnd,
       status,processingStatus,page);
        for (DimissionInfoDto dimissionInfoDto:recordList){
            Long orgId = dimissionInfoDto.getOrgId();
            String orgNameById = jobController.getOrgNameById(orgId);
            dimissionInfoDto.setOrgname(orgNameById);
            Long unitId = dimissionInfoDto.getUnitId();
            String unitname = jobController.getOrgNameById(unitId);
            dimissionInfoDto.setUnitname(unitname);
            Long jobId = dimissionInfoDto.getJobId();
            String jobName = jobController.getJobName(jobId);
            dimissionInfoDto.setJobname(jobName);
        }
        page.setRecords(recordList);
        return  R.ok(new PageResult<DimissionInfoDto>(page));
    }

    @PostMapping("/updateDimissionSettlement")
    @ApiOperation(value="修改员工离职结算信息")
    @Transactional
    public R updateDimissionSettlement(@RequestBody @Valid DimissionSettlemntVo dimissionSettlemntVo, HttpServletRequest request) throws Exception {

        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
      if(ObjectUtils.isEmpty(userInfo)){ return R.error("请先登录");}
        if (!userInfo.getString("usercode").equals(dimissionSettlemntVo.getApplyCode())){
            return R.error("您不能修改其他人的离职结算信息");
        }
        DimissionSettlementEntity dimissionSettlementEntity=BeanUtilsMabach.doToDto(dimissionSettlemntVo,DimissionSettlementEntity.class);
       DimissionInfoEntity dimissionInfoEntit=  dimissionInfoService.getByIdE(dimissionSettlementEntity.getDimissionId());
        ArrayList<String> fileUrlList=dimissionSettlemntVo.getUrlIdsList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(dimissionInfoEntit.getOid(), fileUrlList, "离职结算附件",8);
        }
        dimissionSettlementEntity.setAnnexUrl(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));

        return   dimissionSettlementService.updateByIdE(dimissionSettlementEntity);
    }

    @DeleteMapping("/deleteDimissionSettlement")
    @ApiOperation(value = "删除员工离职结算信息")
    @Transactional
    public R deleteDimissionSettlement(@RequestParam(value = "id" ) String id){
        DimissionSettlementEntity dimissionSettlementEntity = dimissionSettlementDao.selectOne(new QueryWrapper<DimissionSettlementEntity>().eq("id",id).eq("is_delete", 0));
        if(!org.springframework.util.ObjectUtils.isEmpty(dimissionSettlementEntity)) {
            dimissionSettlementEntity.setIsDelete(1);
            dimissionSettlementDao.updateById(dimissionSettlementEntity);
        }
        return R.ok();
    }

    @GetMapping("/getEmployessInfoByCode")
    @ApiOperation(value="根据code 查找员工信息")
    public R<OldEmployeeEntity> isNewOrReinstate(HttpServletRequest request) throws Exception{
        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        if(ObjectUtils.isEmpty(userInfo)){ return R.error("请先登录");}
        String usercode=userInfo.getString("usercode");
        List<EmployeeInfoEntity> employeeInfoEntitys = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("code", usercode).eq("is_delete", 0).orderByDesc("create_time"));
        EmployeeModelDto employeeModelDto;
        if (!CollectionUtils.isEmpty(employeeInfoEntitys)) {
            //  employeeModelDto = BeanUtilsMabach.doToDto(employeeInfoEntitys.get(0), EmployeeModelDto.class);
            return R.ok(employeeInfoEntitys.get(0));
        }
        //        先去查询本地库，如果有则返回最新的那条
//如果本地库没有，则去sqlServer查询
        EmployeeInfoEntity employeeInfoEntity = commonService.finEmpFromMssqlByCode(usercode);
        // employeeModelDto = findEmpByIdByCode(code);
        if (org.springframework.util.ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.ok();
        }
        return R.ok(employeeInfoEntity);
    }




    //附件保存
    public void saveFile(Long oid, ArrayList<String> fileList, String name, Integer type){
        for (String s : fileList) {
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("url", s).eq("type", type));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setName(name);
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setType(type);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlEntity.setUrl(s);
            imgUrlService.saveE(imgUrlEntity);
        }

    }
    public String ListToString(ArrayList<String> fileUrlList){
        String Url="";
        for ( String s:fileUrlList){
            Url+=s+",";
        }
        return Url.substring(0,Url.length()-1);
    }

    //生成流程编号
    public String getDimissionInfoNum(){
        Date date = new Date();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = format.format(date);
        String nm = new SimpleDateFormat("yyyyMMdd").format(date);
        Long max = dimissionInfoDao.getDimissionInfoNum(datestr)+1;
        String employeeOidStr = String.format("%05d", max);
        return "ZF" + nm+employeeOidStr;
    }

}
